import { http } from '@/common/service/service.js' 
import configService from '@/common/service/config.service.js';
import axios from '@/common/axios/axios.js'
import {ACCESS_TOKEN,REFRESH_TOKEN,EXPIRES_IN_TOKEN,SCOPE_TOKEN,TOKEN_TYPE,USER_NAME,USER_INFO} from '@/common/util/constants.js'
import store from '@/store/index.js';
const apiService = {
	 
	 /**
	  * 刷新token
	  * @param {Object} params
	  */
	 async refreshToken(params){
		// 发请求，刷新token
		// 注意：不能用request发，会死循环，因为request设置了请求拦截器，会注入老token
		// 用axios发请求
		const { data } = await axios({
		  url: configService.apiUrl+'/api-auth/user/login',
		  method: 'post',
		  headers: {
			 'Content-Type': 'application/json;charset=UTF-8'
		  },
		  data:params
		})
		
		if(data.code != 200){
			console.log("刷新token失败",data);
			uni.removeStorageSync(ACCESS_TOKEN);
			uni.removeStorageSync(REFRESH_TOKEN);
			uni.removeStorageSync(EXPIRES_IN_TOKEN);
			uni.removeStorageSync(SCOPE_TOKEN);
			uni.removeStorageSync(TOKEN_TYPE);
			store.commit('SET_TOKEN', '')
			store.commit('SET_REFRESH_TOKEN', '')
			store.commit('SET_EXPIRES_IN_TOKEN', 0)
			store.commit('SET_SCOPE_TOKEN', '')
			store.commit('SET_TOKEN_TYPE', '')
			uni.removeStorageSync(USER_INFO);
			store.commit('SET_AVATAR', '')
			store.commit('SET_NAME', { username: '',realname: ''})
			tip.error('登录已过期',true,3000)
			  setTimeout(() => {
				window.location.reload()
			  }, 3000);
		}else {
			console.log("刷新token成功",data);
			const result = data.content.tokenInfo
			uni.setStorageSync(ACCESS_TOKEN,result.access_token);
			uni.setStorageSync(REFRESH_TOKEN,result.refresh_token);
			uni.setStorageSync(EXPIRES_IN_TOKEN,result.expires_in);
			uni.setStorageSync(SCOPE_TOKEN,result.scope);
			uni.setStorageSync(TOKEN_TYPE,result.token_type);
			store.commit('SET_TOKEN', result.access_token);
			store.commit('SET_REFRESH_TOKEN', result.refresh_token);
			store.commit('SET_EXPIRES_IN_TOKEN', result.expires_in);
			store.commit('SET_SCOPE_TOKEN', result.scope);
			store.commit('SET_TOKEN_TYPE', result.token_type);		
		}		
		return data;
	 },
	 /**
	   * 登录
	   */
	 appEdit(params) {
	 	return http.post('/api-auth/user/appEdit',params)	
	 },
	 /**
	  * 登录
	  */
	login(params) {
		return http.post('/api-auth/user/login',params)	
	},
	/**
	  * 手机号码登录
	  */
	phoneNoLogin(params) {
		return http.post('/sys/phoneLogin',params);
	},
	/**
	  * 退出
	  */
	logout(params) {
		return http.post('/api-auth/user/logout',params);
	},
	/**
	  * 获取用户信息
	  */
	me(params) {
		return http.post('/api-auth/user/me',params)	
	},
	/**
	 * 获取文件访问路径
	 * @param avatar
	 * @param subStr
	 * @returns {*}
	 */
	getFileAccessHttpUrl(avatar,subStr){
	    if(!subStr) subStr = 'http'
	    if(avatar && avatar.startsWith(subStr)){
	        return avatar;
	    }else{
	        return configService.staticDomainURL + "/" + avatar;
	    }
	}
};

export default apiService;
